package com.article.controller;

import com.article.lucene.ArticleIndex;
import com.article.model.AdminInfo;
import com.article.model.ArticleInfo;
import com.article.service.AdminInfoService;
import com.article.service.ArticleInfoService;
import com.article.utils.PageUtil;
import com.article.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/5/4.
 */
@RestController
@RequestMapping("/search")
public class SearchController {
    private final static Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Autowired
    private ArticleInfoService articleInfoService;
    @Autowired
    private AdminInfoService adminInfoService;
    //文章索引
    private ArticleIndex articleIndex = new ArticleIndex();


    @RequestMapping(value = "/query")
    public ModelAndView query(@RequestParam(name = "pageIndex", required = false) String pageIndex,
                              @RequestParam(name = "key", required = false) String key, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("mainPage", "foreground/article/result.ftl");
        mav.setViewName("mainTemp");
        try {
            List<ArticleInfo> articleInfoList = new ArrayList<ArticleInfo>();
            if (StringUtil.isEmpty(pageIndex)) {
                pageIndex = "1";
            }
            // 查询参数
            StringBuffer param = new StringBuffer();
            if (StringUtil.isEmpty(key)) {
                key = "";
            } else {
                param.append("key=" + key);
            }
            articleInfoList = articleIndex.searchArticle(key);
            Integer toIndex = articleInfoList.size() >= Integer.parseInt(pageIndex) * 10 ? Integer.parseInt(pageIndex) * 10 : articleInfoList.size();

            mav.addObject("pageCode", PageUtil.genPagination(request.getContextPath() + "/search/query",
                    articleInfoList.size(), Integer.parseInt(pageIndex), 10, param.toString()));
            mav.addObject("articleList", articleInfoList.subList((Integer.parseInt(pageIndex) - 1) * 10, toIndex));
            mav.addObject("resultTotal", articleInfoList.size());
            mav.addObject("pageTitle", "搜索关键字'" + key + "'结果页面");
            mav.addObject("key", key);
            return mav;
        } catch (Exception e) {
            e.printStackTrace();
            mav.addObject("pageCode", PageUtil.genPagination(request.getContextPath() + "/index.html",
                    0, Integer.parseInt(pageIndex), 10, ""));
            mav.addObject("articleList", null);
            mav.addObject("resultTotal", 0);
            mav.addObject("pageTitle", "搜索异常");
            mav.addObject("key", key);
            return mav;
        }
    }

    @RequestMapping(value = "/article/{id}", method = RequestMethod.GET)
    public ModelAndView details(@PathVariable("id") Long id, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("mainTemp");
        mav.addObject("mainPage", "foreground/article/view.ftl");
        try {
            ArticleInfo articleInfo = articleInfoService.getById(id);
            String keyWords = articleInfo.getKeyWord();
            if (StringUtil.isNotEmpty(keyWords)) {
                String arr[] = keyWords.split(" ");
                mav.addObject("keyWords", StringUtil.filterWhite(Arrays.asList(arr)));
            } else {
                mav.addObject("keyWords", null);
            }
            // 点击次数加1
            articleInfo.setClickHit(articleInfo.getClickHit() + 1);
            articleInfoService.update(articleInfo);
            if (articleInfo != null) {
                mav.addObject("article", articleInfo);
                AdminInfo adminInfo = adminInfoService.getById(articleInfo.getAdminId());
                AdminInfo showAdmin = new AdminInfo();
                showAdmin.setAccount(adminInfo.getAccount());
                showAdmin.setNickName(adminInfo.getNickName());
                mav.addObject("showUser", showAdmin);
            }
            mav.addObject("pageCode", this.genUpAndDownPageCode(articleInfoService.getLastArticle(id),
                    articleInfoService.getNextArticle(id), request.getServletContext().getContextPath()));
            mav.addObject("pageTitle", articleInfo.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
            mav.addObject("pageTitle", "浏览异常");
        }
        return mav;
    }

    /**
     * 获取下一篇博客和下一篇博客代码
     *
     * @param lastArticleInfo
     * @param nextArticleInfo
     * @return
     */
    private String genUpAndDownPageCode(ArticleInfo lastArticleInfo, ArticleInfo nextArticleInfo, String projectContext) {
        StringBuffer pageCode = new StringBuffer();
        if (lastArticleInfo == null || lastArticleInfo.getId() == null) {
            pageCode.append("<p>上一篇：没有了</p>");
        } else {
            pageCode.append("<p>上一篇：<a href='" + projectContext + "/search/article/" + lastArticleInfo.getId() + "'>" + lastArticleInfo.getTitle() + "</a></p>");
        }
        if (nextArticleInfo == null || nextArticleInfo.getId() == null) {
            pageCode.append("<p>下一篇：没有了</p>");
        } else {
            pageCode.append("<p>下一篇：<a href='" + projectContext + "/search/article/" + nextArticleInfo.getId() + "'>" + nextArticleInfo.getTitle() + "</a></p>");
        }
        return pageCode.toString();
    }

}
